<?php


namespace App\Http\Middleware;


use Illuminate\Auth\AuthenticationException;
use Illuminate\Support\Facades\Auth;
use Laravel\Passport\Exceptions\MissingScopeException;

class CheckForAnyScope
{
	/**
	 * Handle the incoming request.
	 *
	 * @param  \Illuminate\Http\Request  $request
	 * @param  \Closure  $next
	 * @param  mixed  ...$scopes
	 * @return \Illuminate\Http\Response
	 * @throws \Illuminate\Auth\AuthenticationException|\Laravel\Passport\Exceptions\MissingScopeException
	 */
	public function handle($request, $next, ...$scopes)
	{
		if (! Auth::guard('api')->user() || ! Auth::guard('api')->user()->token()) {
			throw new AuthenticationException;
		}
		
		foreach ($scopes as $scope) {
			if (Auth::guard('api')->user()->tokenCan($scope)) {
				return $next($request);
			}
		}
		
		throw new MissingScopeException($scopes);
	}
}